package com.eliza.demo.qq.fg

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.TextView
import androidx.navigation.Navigation
import com.eliza.demo.R
import com.eliza.library.dao.QQUserDatabase
import com.eliza.library.tools.InfoTools
import com.eliza.library.tools.file.SharedPreferencesTools

class QQLoginFragment : Fragment() {
    private val QQ_SAVE_SP = "QQ_SAVE_SP" //sp文件名
    lateinit var thisView: View
    lateinit var qq_et_name: EditText
    lateinit var qq_et_password: EditText
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_qq_login, container, false)
        thisView = view
        qq_et_name = view.findViewById<EditText>(R.id.qq_et_name)
        qq_et_password = view.findViewById<EditText>(R.id.qq_et_password)

        view.findViewById<ImageButton>(R.id.qq_btn_login).setOnClickListener {
            parentFragment?.context?.let {
                spSave(it)
            }
        }
        /*
        * 跳转界面
        * */
        view.findViewById<Button>(R.id.qq_btn_register).setOnClickListener {
            Navigation.findNavController(view).apply {
                navigate(R.id.action_QQLoginFragment_to_QQRegisterFragment)
            }
        }

        return view
    }

    private fun spSave(context: Context) {
        val read = SharedPreferencesTools.read(context, QQ_SAVE_SP)
        if (qq_et_name.text.isNullOrEmpty() || qq_et_password.text.isNullOrEmpty()) {
            InfoTools.ToastTools(context, "请填写账号名或密码”")
        } else if (qq_et_name.text.length < read?.getString("QQ_NAME", "Nil")?.length ?: 10) {
            InfoTools.ToastTools(context, "账号名或密码错误")
        } else {
            InfoTools.ToastTools(context, "登录成功")
        }
        /*QQ登陆 并存入数据
        * * /data/data/com.eliza.save/shared_prefs/QQ_SAVE_SP.xml*/
        SharedPreferencesTools.save(context, QQ_SAVE_SP, HashMap<String, String>().apply {
            put("QQ_NAME", qq_et_name.text.toString() ?: "")
            put("QQ_PSW", qq_et_password.text.toString() ?: "")
        })
        /*展示数据*/
        thisView.findViewById<TextView>(R.id.qq_tv_show).text =
            "${read?.getString("QQ_NAME", "Nil")}/n${read?.getString("QQ_PSW", "null")}"

    }

}